<?php

namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketSite;
use addons\cloud_market\model\CloudMarketSiteAddon;
use addons\cloud_market\model\CloudMarketSiteAddonToken;
use addons\cloud_market\model\CloudMarketDeveloper;
use addons\cloud_market\utils\LocalApi;
use hiduoke\services\FormBuilder as Form;

/**
 * 站点接口
 */
class Site extends CloudMarketApiController
{
    protected $notApiLogin = [];
    protected $notApiCheck = '*';
    /**
     * @var CloudMarketSite
     */
    protected $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketSite();
    }
    /***************************商城使用***************************************/

    /**
     * 【商城】获取站点信息
     */
    public function getSite()
    {
        $site_id = input('site_id', 0);
        $site = $this->model->where(['id' => $site_id])->find();
        $site['createtime'] = date("Y-m-d H:i:s", $site['createtime']);
        return $this->success('', $site);
    }

    /**
     * 【商城】获取站点列表
     */
    public function getSiteList()
    {
        $where = [];
        $keyword = input('keyword', '');
        if($keyword){
            // 同时搜索站点名称和域名
            $where[] = ['title|domain', 'like', "%{$keyword}%"];
        }
        $data = $this->model
            ->where(['user_id' => $this->getUser()->id])
            ->where($where)
            ->order('id desc')
            ->paginate([
                'list_rows' => input('size',10),
                'page'      => input('page',1)
            ], false)
            ->each(function ($item, $key) {
                $item['addon_count'] = CloudMarketSiteAddon::where(['site_id' => $item['id']])->count();
                return $item;
            });
        return $this->success('', $data);
    }

    public function getSiteForm($id)
    {
        $row = $this->model->findOrEmpty($id);//创建表单
        $action = $this->request->domain() . "/api.site/save?id=" . $id;
        $form = Form::createForm($action)->setMethod("POST");
        //新增表单
        $rule = [
            Form::input('title', '站点名称', $row['title'] ?? '')->required(),
            Form::input('token', '站点Token', $row['token'] ?? '')
                ->effect(['help' => '对应站点的Token，请勿随意修改，如二者Token不一致，请修改此处'])->required(),
        ];
        $title = "编辑站点";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    public function save($id)
    {
        $row = $this->model->findOrEmpty($id);
        $formData = getFormData();
        $row->save($formData);
        return $this->success("保存成功");
    }

    /**
     * 【商城】获取站点下已购买的应用列表
     * @throws \think\db\exception\DbException
     */
    public function getSiteAddonList()
    {
        $page = input('page', 1);
        $size = input('size',5);
        $site_id = input('site_id', 0);
        $data = (new CloudMarketSiteAddon())
            ->where(['site_id' => $site_id])
            ->paginate([
                'list_rows' => $size,
                'page'      => $page
            ], false)
            ->append(['addon','site','ServicetimeMan'])
            ->each(function ($item, $key) {
                $addon = $item->addon;
                 $dev = CloudMarketDeveloper::where(['user_id' => $addon['user_id']])->find();
                $item['used_count'] = CloudMarketSiteAddonToken::where(['site_id' => $item['site_id'], 'aid' => $item['addon_id']])->count();
                 $item['title'] = $addon['title'];
                 $item['name'] = $addon['name'];
                 $item['type'] = $addon['type'];
                 $item['icon_image_url'] = $addon['icon_image_url'];
                 $item['new_version'] = $addon['new_version'];
                 $item['dev_name'] = $dev['name'];
                 $item['dev_phone'] = $dev['phone'];
                 $item['servicetime_man'] = $item->ServicetimeMan;
                return $item;
            });
        return $this->success('', $data);
    }

    /**
     * 获取站点应用Token
     */
    public function getSiteAddonTokenList()
    {
        $SiteAddonToken = new CloudMarketSiteAddonToken();
        $page = input('page', '0');
        $site_id = input('site_id', 0);
        $aid = input('aid', 0);
        $data = $SiteAddonToken
            ->where(['site_id' => $site_id, 'aid' => $aid])
            ->paginate([
                'list_rows' => 10,
                'page'      => $page
            ], false)
            ->each(function ($item, $key) {
                $item['short_token'] = substr($item->token, 0, 8) . "...";
                $item['createtime'] = date("Y-m-m H:i:s", $item['createtime']);
                return $item;
            });
        return $this->success('', $data);
    }

    // TODO 这个要配合那边优化一下
    public function getPlatformMsg($token,$type, $site_id)
    {
        $site = (new CloudMarketSite())->where(['id' => $site_id])->find();
        $res = (new LocalApi($site))->getPlatformMsg($token,$type);
        if ($res['code'] == 0) {
            return $this->success('同步成功', $res['data']);
        } else {
            return $this->error($res['msg'] ?: '获取失败');
        }
    }

    /**
     * 重置站点token【目前不知道行不行】
     */
    public function resetSiteAddonToken()
    {
        $id = input('addon_token_id', '');
        $site_addon_token = (new CloudMarketSiteAddonToken())->where(['id' => $id])->find();
        if (!$site_addon_token) {
            return $this->error("token不存在");
        }
        $where = ['user_id' => $this->getUser()['id'], 'id' => $site_addon_token['site_id']];
        $site = (new CloudMarketSite())->where($where)->find();
        if (!$site) {
            return $this->error("token错误");
        }
        $site_addon = (new CloudMarketSiteAddon())->where(['site_id' => $site['id'], 'addon_id' => $site_addon_token['aid']])->find();
        if ($site_addon['reset_count'] >= ($site_addon['count'] * 3)) {
            return $this->error("重置次数已用完，无法重置", $site_addon);
        }
        $site_addon_token->delete();
        (new CloudMarketSiteAddon())->where(['site_id' => $site['id']])->inc('reset_count', 1)->update();
        return $this->success("重置成功");
    }


    /**
     * 获取站点下的api列表
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function getApiSiteList()
    {
        $id = input('site_id', 0);
        // TODO: 需要创建对应的 CloudMarketApiSite 模型
        // $data = (new CloudMarketApiSite())
        //     ->where(['site_id' => $id])->order('id desc')
        //     ->append(['api', 'group', 'site_api_token'])
        //     ->paginate(10, false)->toArray();
        $data = ['data' => []]; // 临时返回空数据
        foreach ($data['data'] as $key => $value) {
            $res = [
                'id'             => $value['id'],
                'site_id'        => $value['site_id'],
                'api_id'         => $value['api']['id'],
                'group_id'       => $value['api']['api_group_id'],
                'name'           => $value['api']['name'],
                'icon'           => $value['api']['config']['icon'],
                'unit'           => $value['api']['config']['unit'] ?? '次',
                'desc'           => $value['api']['desc'],
                'site_api_token' => false,
            ];
            if ($value['site_api_token']) {
                $res['site_api_token'] = true;
//                $res['api_token'] = $value['site_api_token'];
                $res['site_token'] = $value['site_api_token']['site_token'];
                $res['api_type'] = $value['site_api_token']['type'];
                $res['pid'] = $value['site_api_token']['pid'];
                $res['billing_time'] = $value['site_api_token']['billing_time'];
                $res['pay_type'] = $value['site_api_token']['pay_type'];
                $pay_type_names = array(
                    '0' => '无周期',
                    '1' => '每日',
                    '2' => '每月',
                    '3' => '每年',
                );
                $res['pay_type_name'] = $pay_type_names[$value['site_api_token']['pay_type']];
                $res['count'] = $value['site_api_token']['count'];
                $res['used_count'] = $value['site_api_token']['used_count'];
                $res['cycle_limit'] = $value['site_api_token']['cycle_limit'];
                $res['cycle_used'] = $value['site_api_token']['cycle_used'];
                $res['cycle_time'] = $value['site_api_token']['cycle_time'];
                /// 刷新时间
                $pay_type_day = [
                    '0' => 0,
                    '1' => 1,
                    '2' => 30,
                    '3' => 365,
                ];
                $res['percentage'] = ($res['cycle_limit'] - $res['cycle_used']) / ($res['cycle_limit'] ?: 1) * 100;
                $res['cycle_refresh_time'] = $value['site_api_token']['cycle_time'] + $pay_type_day[$value['site_api_token']['pay_type']] * 86400;
                $res['cycle_refresh_time'] = date('Y-m-d H:i:s', $res['cycle_refresh_time']);
            }
            $data['data'][$key] = $res;
        }
        return $this->success('', $data);
    }


    public function getApiAddonTokenList()
    {
        $token = input('token', '');
        // TODO: 需要创建对应的 CloudMarketApiAddonToken 模型
        // $data = (new CloudMarketApiAddonToken())
        //     ->where(['token' => $token])->order('id desc')
        //     ->append(['api', 'group', 'api_addon_token'])
        //     ->paginate(10, false)->toArray();
        $data = ['data' => []]; // 临时返回空数据
        foreach ($data['data'] as $key => $value) {
            $res = [
                'id'              => $value['id'],
                'token'           => $value['token'],
                'api_id'          => $value['api']['id'],
                'group_id'        => $value['api']['api_group_id'],
                'name'            => $value['api']['name'],
                'icon'            => $value['api']['config']['icon'],
                'unit'            => $value['api']['config']['unit'] ?? '次',
                'desc'            => $value['api']['desc'],
                'api_addon_token' => false,
            ];
            if ($value['api_addon_token']) {
                $res['api_addon_token'] = true;
//                $res['api_token'] = $value['api_addon_token'];
                $res['addon_token'] = $value['api_addon_token']['addon_token'];
                $res['addon_name'] = $value['api_addon_token']['addon_name'];
                $res['pid'] = $value['api_addon_token']['pid'];
                $res['billing_time'] = $value['api_addon_token']['billing_time'];
                $res['pay_type'] = $value['api_addon_token']['pay_type'];
                $res['api_type'] = $value['api_addon_token']['type'];// 0 应用 1 站点
                $pay_type_names = array(
                    '0' => '无周期',
                    '1' => '每日',
                    '2' => '每月',
                    '3' => '每年',
                );
                $res['pay_type_name'] = $pay_type_names[$value['api_addon_token']['pay_type']];
                $res['count'] = $value['api_addon_token']['count'];
                $res['used_count'] = $value['api_addon_token']['used_count'];
                $res['cycle_limit'] = $value['api_addon_token']['cycle_limit'];
                $res['cycle_used'] = $value['api_addon_token']['cycle_used'];
                $res['cycle_time'] = $value['api_addon_token']['cycle_time'];

                /// 刷新时间
                $pay_type_day = [
                    '0' => 0,
                    '1' => 1,
                    '2' => 30,
                    '3' => 365,
                ];
                $res['percentage'] = ($res['cycle_limit'] - $res['cycle_used']) / ($res['cycle_limit'] ?: 1) * 100;
                $res['cycle_refresh_time'] = $value['api_addon_token']['cycle_time'] + $pay_type_day[$value['api_addon_token']['pay_type']] * 86400;
                $res['cycle_refresh_time'] = date('Y-m-d H:i:s', $res['cycle_refresh_time']);
            }
            $data['data'][$key] = $res;
        }
        return $this->success('', $data);
    }






}
